﻿using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL.Base
{
   public class CodeDAL
    {
        public readonly SqlDbHelper _dbHelper;
        public CodeDAL()
        {
            _dbHelper = new SqlDbHelper();
        }

        /// <summary>
        /// 根据编码名称(Name)获取编码内容
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public List<CodeModel> GetArea(string name)
        {
            string sql = $"  select * from base_code where parentid in ( select id from base_code where name=@name)";
            SqlParameter para = new SqlParameter("@name", name);
            DataTable dt = _dbHelper.executeSqlDataTable(sql,para);
            var data = _dbHelper.DataTableToList<CodeModel>(dt);
            return data.ToList();
        }

        /// <summary>
        /// 新增编码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddCode(CodeModel model)
        {
            string sql = @"INSERT INTO [dbo].[Base_Code]
                                    ([Id]
                                    ,[Code]
                                    ,[Name]
                                    ,[Value]
                                    ,[Sort]
                                    ,[ParentId])
                                VALUES
                                    (@Id,
                                    @Code, 
                                    @Name,
                                    @Value, 
                                    @Sort,
                                    @ParentId)";

            SqlParameter[] paras = new SqlParameter[] {
                            new SqlParameter("@Id",model.Id),
                            new SqlParameter("@Code",model.Code ?? ""),
                            new SqlParameter("@Name",model.Name ?? ""),
                            new SqlParameter("@Value",model.Value ?? ""),
                            new SqlParameter("@Sort",model.Sort ?? 0),
                            new SqlParameter("@ParentId",model.ParentId ?? ""),
            };
            int success = _dbHelper.executeSqlNonQuery(sql, paras);
            return success > 0;
        }
    }
}
